package server.utilities;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Class used to manage cookies
 * @author Romain Pellerin
 */
public class CookieManager {
	
	/**
	 * Tries to retrieve any nickname saved in a cookie.
	 * @param request The HTTP request
	 * @param cookie The name of the cookie to look for
	 * @return Any nickname saved in a cookie, or null when there's none
	 */
	public static String getSavedCookie(HttpServletRequest request, String cookie) {
		Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookiee : cookies) {
                if (cookiee != null && cookie.equals(cookiee.getName()))
                    return cookiee.getValue();
            }
        }
        return null;
	}
	
	/**
	 * Save the user's nickname in a cookie, for 3 months
	 * @param user The nickname that will be saved
	 * @param response The HTTP response
	 */
	public static void saveNickname(String nickname, HttpServletResponse response) {
		Cookie cookie = new Cookie("nickname", nickname);
	    cookie.setMaxAge(60*60*24*30*3); // 3 months
	    response.addCookie(cookie);
	}

}
